package com.huatai.vba.execute.handler;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.common.collect.Lists;
import com.huatai.vba.common.utils.FileUtils;
import com.huatai.vba.dal.model.VbaFileHandler;
import com.huatai.vba.dal.model.VbaFileHandlerRecord;

@Service("copyFileExecuteService")
public class CopyFileExecuteServiceImpl extends ExecuteService {

	@SuppressWarnings("unchecked")
	@Override
	public VbaFileHandlerRecord handler(VbaFileHandler handler) throws Exception {
		List<String> fileRegulars = (List<String>) JSONUtils.parse(handler.getHandlerFileRegular());
		List<File> list = Lists.newArrayList();
		for (String s : fileRegulars) {
			if (StringUtils.isBlank(s))
				continue;
			File[] fs = FileUtils.findFiles(new File(handler.getHandlerSource()), s);
			list.addAll(Lists.newArrayList(fs));
		}
		File[] files = list.toArray(new File[list.size()]);
		FileUtils.copy(files, new File(handler.getHandlerDestination()));
		StringBuffer fileNames = new StringBuffer();
		for (File f : files) {
			fileNames.append(f.getName());
			fileNames.append(";");
		}
		VbaFileHandlerRecord record = new VbaFileHandlerRecord();
		record.setFileNames(fileNames.toString());
		record.setFileNum(files.length);
		return record;
	}

}
